package logic

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/models/mysql"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodAddLogic) GoodAdd(in *goodsrpc.GoodAddRequest) (*goodsrpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line
	var findGood mysql.Good
	begin := mysql.DB.Begin()
	err := findGood.FindGoods(begin, in.Name)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("当前商品已存在")
	}
	class := &mysql.Class{
		Name: in.ClassName,
	}
	err = class.FindClassByName(begin, in.ClassName)
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	goods := &mysql.Good{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}
	err = goods.GoodAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &goodsrpc.GoodAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
